package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;

public class NotificationsService extends Service {

	private NotificationManager myNotificationManager;
	private DefaultHttpClient httpclient;
	private String username,password;
	private SharedPreferences prefs;
	
	public void onCreate() {
		super.onCreate();
		if(Common.HIGHDEBUG)
			Log.d(Common.SERVICE_TAG,"onCreate()");

		prefs = PreferenceManager.getDefaultSharedPreferences(this) ;
		username = prefs.getString("emailPref",null);
		password = prefs.getString("passwordPref",null);
		
		myNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
		
		httpclient = new DefaultHttpClient();
		Cookie cookie = Common.recupCookie(this);
		httpclient.getCookieStore().addCookie(cookie);
		httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		if(Common.HIGHDEBUG)
			Log.d(Common.SERVICE_TAG,"onStartCommand()");
		new GetFriendsTLTask().execute();
		
		return START_STICKY;
	}

	public void onDestroy() {
		super.onDestroy();
		if(Common.HIGHDEBUG)
			Log.d(Common.SERVICE_TAG,"onDestroy()");
	}
	
	private void makeNotification(JSONArray jPhotos){
		int countNew = countNewPhotos(jPhotos);
		
		int countOld = prefs.getInt("countPhotos", 0); //Notifs deja présentes
		int totalPhotos = countNew + countOld;
		
		CharSequence contentText = null,contentTitle = null;
		String photoURL=null;
		
		if(countNew==0){
			if(Common.DEBUG)
				Log.d(Common.SERVICE_TAG,"no new photo");
			long current = System.currentTimeMillis();
			prefs.edit().putString("latestServiceRun",String.valueOf(current)).commit();
		}else{
			if(Common.DEBUG)
				Log.d(Common.SERVICE_TAG,"new photo(s): "+countNew);
			CharSequence tickerText = null;
			
			if(totalPhotos==1){
				tickerText = getString(R.string.newPhoto);
				try {
					contentTitle = jPhotos.getJSONObject(0).getString("username");
					contentText = jPhotos.getJSONObject(0).getString("shout")+" @ "+jPhotos.getJSONObject(0).getString("venuename");
					photoURL = Common.getBaseImgsUrl()+jPhotos.getJSONObject(0).getString("url");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			else{
				tickerText = totalPhotos+" "+getString(R.string.newPhotos);
				contentTitle = getString(R.string.newPhotos);
				contentText = totalPhotos+" "+getString(R.string.newPhotos);
			}	
			
			int icon = R.drawable.logo;
			long when = System.currentTimeMillis();
	
			Notification notification = new Notification(icon, tickerText, when);
//			notification.flags = Notification.FLAG_AUTO_CANCEL;
			notification.defaults |= Notification.DEFAULT_LIGHTS;
			notification.defaults |= Notification.DEFAULT_VIBRATE;
			
			Context context = getApplicationContext();
			PendingIntent contentIntent;
//			if(count==1 && photoURL!=null){
//				Intent notificationIntent = new Intent(this, FullscreenPicture.class);
//				Bundle extras = new Bundle();
//				extras.putString("uri",photoURL);
//				notificationIntent.putExtras(extras);
//				contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//			}else{
//				Intent notificationIntent = new Intent(this,FriendsTimeline.class);
//				Bundle extras = new Bundle();
//				extras.putString("username",username);
//				extras.putString("password",password);
//				notificationIntent.putExtras(extras);
//				contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
//			}
			
			Intent notificationIntent = new Intent(this,NotificationsClick.class);
			Bundle extras = new Bundle();
			extras.putString("username",username);
			extras.putString("password",password);
			if(totalPhotos==1 && photoURL!=null)
				extras.putString("uri",photoURL);
			
			notificationIntent.putExtras(extras);
			contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
	
			notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
			String notifId = String.valueOf(when);
			int nId=1;

			myNotificationManager.notify(String.valueOf(nId),nId,notification);
			prefs.edit().putInt("countPhotos",totalPhotos).commit();
			saveLatestRun(jPhotos);
		}
	}
	
	private void saveLatestRun(JSONArray jPhotos){
		String time = null;
		try {
			time = jPhotos.getJSONObject(0).getString("millis");
			prefs.edit().putString("latestServiceRun",time).commit();
		} catch (JSONException e) {
			if(Common.HIGHDEBUG)
				Log.d(Common.SERVICE_TAG,e.getMessage());
		}
		if(Common.HIGHDEBUG)
			Log.d(Common.SERVICE_TAG,"Saved latestRun="+time);
	}
	
	private int countNewPhotos(JSONArray jPhotos){
		int i=-1;
		String newTime=null;
		String latestRun = prefs.getString("latestServiceRun","0");
		do{
			i++;
			try {
				newTime = jPhotos.getJSONObject(i).getString("millis");
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}while(newTime.compareTo(latestRun)>0);
		return i;
	}
	
	private void onThreadCompleted(Bundle data){
		if(!data.containsKey("eMessage")){
			if(Common.HIGHDEBUG)
				Log.d(Common.SERVICE_TAG,"onThreadCompleted()");
			JSONArray jReponse=null;
			try{
				jReponse = new JSONArray(data.getString("reponse"));
				makeNotification(jReponse);
			}catch(JSONException e){
				Log.e(Common.SERVICE_TAG,"Error while parsing response: "+e.getMessage());
			}
		}else{
			Log.e(Common.SERVICE_TAG,data.getString("eMessage"));
		}
		stopSelf();
	}
	
	private class GetFriendsTLTask extends AsyncTask<Boolean,String,Message>{

		protected Message doInBackground(Boolean... parameters) {
			Message msg = Message.obtain();
			Bundle data = new Bundle();
			String urlTimeline = Common.getBaseUrl()+"/latestfriendsphotos";
			String reponse = null;
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("user", username));
				params.add(new BasicNameValuePair("password", password));
				reponse = Common.postUrlData(httpclient, urlTimeline,params);
				data.putString("reponse",reponse);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			onThreadCompleted(msg.getData());
		}
	}
	
	static void schedule(Context context, Integer minutes){
		Intent i = new Intent(context,NotificationsService.class);
		i.putExtra("alarm",true);
		PendingIntent pi = PendingIntent.getService(context,0,i,0);
		
		SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
		long current = System.currentTimeMillis();
		preferences.edit().putString("latestServiceRun",String.valueOf(current)).commit();
//		preferences.edit().putString("latestServiceRun",new String("1291237142")).commit();
		preferences.edit().putInt("countPhotos",0).commit();
		
		long INTERVAL = minutes * 60 * 1000;
		if(Common.HIGHDEBUG)
			Log.d(Common.SERVICE_TAG,"AlarmManager set. interval="+minutes+"-"+INTERVAL);
		AlarmManager aMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		aMgr.cancel(pi);
		aMgr.setRepeating(AlarmManager.RTC,System.currentTimeMillis()+INTERVAL,INTERVAL, pi);
	}
	
	static void unschedule(Context context){
		Intent i = new Intent(context,NotificationsService.class);
		PendingIntent pi = PendingIntent.getService(context,0,i,0);
		
		AlarmManager aMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		aMgr.cancel(pi);
		if(Common.DEBUG){
			Log.d(Common.SERVICE_TAG,"unschedule()");
		}
	}
}
